package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.PurchaseOrderDetail;
import com.geek.factory.entity.Material;
import com.geek.factory.entity.MaterialSupplier;
import com.geek.factory.result.Result;
import com.geek.factory.service.IPurchaseOrderDetailService;
import com.geek.factory.service.IMaterialService;
import com.geek.factory.service.MaterialSupplierService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * 采购明细表前端控制器
 *
 * @author author
 * @since 2025-06-26
 */
@RestController
@RequestMapping("/purchase-order-detail")
@Api(tags = "后台系统的 - 采购明细模块")
@Slf4j
@CrossOrigin
public class PurchaseOrderDetailController {

    @Autowired
    private IPurchaseOrderDetailService purchaseOrderDetailService;
    
    @Autowired
    private IMaterialService materialService;
    
    @Autowired
    private MaterialSupplierService materialSupplierService;

    @ApiOperation("通过ID查询采购明细信息")
    @GetMapping("/{detailId}")
    public Result findPurchaseOrderDetailById(@ApiParam("采购明细ID") @PathVariable("detailId") Integer detailId) {
        PurchaseOrderDetail detail = purchaseOrderDetailService.getById(detailId);
        log.info("purchaseOrderDetail: {}", detail);
        if (detail != null) {
            // 获取原料信息
            Material material = materialService.getById(detail.getMaterialId());
            Map<String, Object> result = new HashMap<>();
            result.put("detail", detail);
            result.put("material", material);
            
            return new Result(SuccessConstant.SUCCESS, "ok", result);
        }
        return new Result(SuccessConstant.FAIL, "采购明细不存在");
    }

    @ApiOperation("获取原料的供应商单价信息")
    @GetMapping("/material-price/{materialId}")
    public Result getMaterialPrice(@PathVariable Integer materialId) {
        try {
            // 获取原料信息
            Material material = materialService.getById(materialId);
            if (material == null) {
                return new Result(SuccessConstant.FAIL, "原料不存在");
            }
            
            // 查找该原料的供应商关系
            List<MaterialSupplier> suppliers = materialSupplierService.lambdaQuery()
                .eq(MaterialSupplier::getMaterialId, materialId)
                .orderByAsc(MaterialSupplier::getUnitPrice) // 按价格升序
                .list();
            
            // 如果找到供应商，返回单价信息
            if (suppliers != null && !suppliers.isEmpty()) {
                MaterialSupplier supplier = suppliers.get(0);
                Map<String, Object> result = new HashMap<>();
                result.put("materialId", materialId);
                result.put("materialName", material.getMaterialName());
                result.put("unitPrice", supplier.getUnitPrice());
                result.put("supplierId", supplier.getSupplierId());
                result.put("unit", material.getUnit());
                return new Result(SuccessConstant.SUCCESS, "获取成功", result);
            } else {
                return new Result(SuccessConstant.FAIL, "未找到该原料的供应商价格信息");
            }
        } catch (Exception e) {
            log.error("获取原料单价失败", e);
            return new Result(SuccessConstant.FAIL, "获取原料单价失败: " + e.getMessage());
        }
    }

    @ApiOperation("新增采购明细")
    @PostMapping
    public Result addPurchaseOrderDetail(@RequestBody PurchaseOrderDetail detail) {
        // 如果没有设置单价，尝试获取原料的供应商单价
        if (detail.getUnitPrice() == null && detail.getMaterialId() != null) {
            List<MaterialSupplier> suppliers = materialSupplierService.lambdaQuery()
                .eq(MaterialSupplier::getMaterialId, detail.getMaterialId())
                .orderByAsc(MaterialSupplier::getUnitPrice)
                .list();
                
            if (!suppliers.isEmpty()) {
                detail.setUnitPrice(suppliers.get(0).getUnitPrice());
            }
        }
        
        // 如果设置了单价和数量，计算金额
        if (detail.getUnitPrice() != null && detail.getQuantity() != null) {
            BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
            detail.setAmount(amount);
        }
        
        boolean isSuccess = purchaseOrderDetailService.save(detail);
        log.info("新增采购明细: {}, 结果: {}", detail, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "新增成功", detail);
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    }

    @ApiOperation("根据ID删除采购明细")
    @DeleteMapping("/{detailId}")
    public Result deletePurchaseOrderDetail(@ApiParam("采购明细ID") @PathVariable("detailId") Integer detailId) {
        boolean isSuccess = purchaseOrderDetailService.removeById(detailId);
        log.info("删除采购明细ID: {}, 结果: {}", detailId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    @ApiOperation("修改采购明细信息")
    @PutMapping("/{detailId}")
    public Result updatePurchaseOrderDetail(@ApiParam("采购明细ID") @PathVariable("detailId") Integer detailId, @RequestBody PurchaseOrderDetail detail) {
        detail.setDetailId(detailId);
        
        // 如果设置了单价和数量，重新计算金额
        if (detail.getUnitPrice() != null && detail.getQuantity() != null) {
            BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
            detail.setAmount(amount);
        }
        
        boolean isSuccess = purchaseOrderDetailService.updateById(detail);
        log.info("修改采购明细: {}, 结果: {}", detail, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "修改成功", detail);
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    @ApiOperation("分页查询采购明细列表")
    @GetMapping("/page")
    public Result getPurchaseOrderDetailPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer purchaseId,
            @RequestParam(required = false) Integer materialId
    ) {
        QueryWrapper<PurchaseOrderDetail> wrapper = new QueryWrapper<>();
        if (purchaseId != null) {
            wrapper.eq("purchase_id", purchaseId);
        }
        if (materialId != null) {
            wrapper.eq("material_id", materialId);
        }

        Page<PurchaseOrderDetail> page = purchaseOrderDetailService.page(new Page<>(current, size), wrapper);
        
        // 丰富明细信息，添加原料名称等
        List<Map<String, Object>> enrichedRecords = new ArrayList<>();
        for (PurchaseOrderDetail detail : page.getRecords()) {
            Map<String, Object> enrichedDetail = new HashMap<>();
            enrichedDetail.put("detail", detail);
            
            // 获取原料信息
            Material material = materialService.getById(detail.getMaterialId());
            if (material != null) {
                enrichedDetail.put("materialName", material.getMaterialName());
                enrichedDetail.put("materialCode", material.getMaterialCode());
                enrichedDetail.put("unit", material.getUnit());
            }
            
            enrichedRecords.add(enrichedDetail);
        }
        
        Map<String, Object> data = new HashMap<>();
        data.put("records", enrichedRecords);
        data.put("total", page.getTotal());
        data.put("current", page.getCurrent());
        data.put("size", page.getSize());
        data.put("pages", page.getPages());

        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }

    @ApiOperation("根据采购订单ID获取明细列表")
    @GetMapping("/purchase/{purchaseId}")
    public Result getDetailsByPurchaseId(@PathVariable Integer purchaseId) {
        QueryWrapper<PurchaseOrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("purchase_id", purchaseId);
        List<PurchaseOrderDetail> list = purchaseOrderDetailService.list(wrapper);
        
        // 丰富明细信息，添加原料名称等
        List<Map<String, Object>> enrichedList = new ArrayList<>();
        for (PurchaseOrderDetail detail : list) {
            Map<String, Object> enrichedDetail = new HashMap<>();
            enrichedDetail.put("detail", detail);
            
            // 获取原料信息
            Material material = materialService.getById(detail.getMaterialId());
            if (material != null) {
                enrichedDetail.put("materialName", material.getMaterialName());
                enrichedDetail.put("materialCode", material.getMaterialCode());
                enrichedDetail.put("unit", material.getUnit());
            }
            
            enrichedList.add(enrichedDetail);
        }
        
        log.info("根据采购订单ID获取明细列表: purchaseId={}, 总数={}", purchaseId, list.size());
        return new Result(SuccessConstant.SUCCESS, "查询成功", enrichedList);
    }

    @ApiOperation("批量删除采购明细")
    @DeleteMapping("/batch")
    public Result batchDelete(@RequestBody List<Integer> detailIds) {
        boolean isSuccess = purchaseOrderDetailService.removeByIds(detailIds);
        log.info("批量删除采购明细: detailIds={}, 结果: {}", detailIds, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "批量删除成功");
        }
        return new Result(SuccessConstant.FAIL, "批量删除失败");
    }
}